import { isEmpty } from './types'

export function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16).toUpperCase()
  })
}

export function serialize(obj) {
  if (typeof obj === 'string') return obj
  let str = ''
  for (const x in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, x)) {
      const n = obj[x]
      const empty = isEmpty(n)
      if (!empty) {
        if (Array.isArray(n)) {
          n.forEach((n0) => (str += `${x}=${n0}&`))
        } else {
          str += `${x}=${n}&`
        }
      }
    }
  }

  return str.substring(0, str.length - 1)
}

export function popupScroll(e, pageNum, totalPage) {
  if (pageNum === totalPage) return
  const { clientHeight, scrollHeight, scrollTop } = e.target
  if (scrollHeight - scrollTop > clientHeight && !loading) {
    return pageNum + 1
  }
}

/**
 * 保留 object 中的部分内容
 * @param obj
 * @param keys
 */
export function pick(obj, keys) {
  const r = {}
  keys.forEach((key) => {
    r[key] = obj[key]
  })
  return r
}

export function toUrl(url) {
  if (!/^(https?:)\/\//i.test(url)) {
    const host = url.split('/')[0]
    if (host.includes('.') || host === 'localhost') {
      url = 'http://' + url
    }
  }
  return url
}
